package com.zhiyun.hxzy;

import com.zhiyun.hxzy.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * EnableWebSecurity注解使得SpringMVC集成Spring Security的web安全支持
 */
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AdminService adminService;

    /**
     * 权限配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置拦截规则
        http.authorizeRequests().antMatchers("/admin/**").hasAnyRole("ADMIN","SUPERADMIN");
        // 配置登录功能
        http.formLogin().usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/admin/login.jsp").permitAll() // 登录页路径
                .loginProcessingUrl("/login") // 登录表单路径
                .failureForwardUrl("/admin/error.jsp").permitAll() // 失败路径
                .defaultSuccessUrl("/admin/index.jsp")//成功路径
                .and().rememberMe()//开启记住我
                .key("unique-and-secret")//密钥
                .rememberMeCookieName("remember-me-cookie-name")//用户存在cookie的键
                .tokenValiditySeconds(60*60*24*30);//cookie存活时间

        // 禁用csrf安全验证
        http.csrf().disable();

        // 注销成功跳转页面
        http.logout().logoutSuccessUrl("/admin/login.jsp");

        //开启记住我功能
        http.rememberMe().rememberMeParameter("remeber");
        http.authorizeRequests().anyRequest().permitAll().and().logout().permitAll();
    }

    /**
     * 放行静态资源
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/admin/css/**","/admin/js/**","/admin/img/**","/admin/plugins/**");
    }

    /**
     * 自定义认证数据源
     */
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception{
        builder.userDetailsService(adminService).passwordEncoder(getPasswordEncoder());
    }

    // 加密工具
    @Bean
    public BCryptPasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}